use super::address::Address;
use crate::{ADDRS, GLOBAL_CONFIG};
use rusqlite::{Connection, Result};

#[tauri::command]
pub fn add_addr(name: &str, tel: &str, tags: Vec<String>) -> String {
    if name.is_empty() {
        return "姓名不能为空".to_string();
    }
    println!("存储数据");
    let addr_id = insert_addr(name, tel, &tags).unwrap();
    println!("存储成功");
    // 更新缓存
    let mut addrs = ADDRS.lock().unwrap();
    let addr = Address::new(addr_id, name.to_string(), tel.to_string(), tags);
    addrs.insert(addr_id, addr);
    "添加成功".to_string()
}

fn insert_addr(name: &str, tel: &str, labels: &Vec<String>) -> Result<i64>{
    let conn = Connection::open(GLOBAL_CONFIG.lock().unwrap().address.db_file.clone()).unwrap();
    conn.execute(
        "INSERT INTO address(name, tel) VALUES (?1, ?2)",
        (name, tel),
    )?;
    let addr_id = conn.last_insert_rowid();
    if labels.len() > 0 {
        for label in labels {
            // 先查询是否已存在该label，不存在时再插入
            let mut stmt = conn.prepare("SELECT id FROM label WHERE label = ?1")?;
            let exist_label_id = stmt.query_row([label], |row| row.get(0));

            let label_id;
            if exist_label_id.is_ok() {
                label_id = exist_label_id.unwrap();
            } else {
                conn.execute("INSERT INTO label (label) VALUES (?1)", [label])?;
                label_id = conn.last_insert_rowid();
            }
            conn.execute("INSERT INTO addr_label (addr_id, label_id) VALUES (?1, ?2)", (addr_id, label_id))?;
        }
    }
    Ok(addr_id)
}